<?php
/**
 * Created by PhpStorm.
 * FileName: wx_notify.php
 * User: Administrator
 * Date: 2018/10/23
 * Time: 11:23
 */

$wxNotify = new WxNotify();
call_user_func_array(array($wxNotify,'index'), array());

class WxNotify {
    //微信支付回调
    public function index(){
        error_reporting(0);
        // 微信公众平台推送过来的post数据
        $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
        // 获取数据
        $data = $this->FromXml($xml);
        if (!$data) {
            echo 'xml数据异常！';
            return $data;
        }
        // 保存微信服务器返回的签名sign
        $data_sign = $data['sign'];
        // sign不参与签名算法
        unset($data['sign']);

        $sign = $this->makeSign($data);
        // 判断签名是否正确  判断支付状态
        if ( ($sign == $data_sign) && ($data['return_code'] == 'SUCCESS') && ($data['result_code'] == 'SUCCESS') ) {
            $result = $data;
            //获取服务器返回的数据
            $url = 'https://www.saixingchi.com/index.php/Api/Order/addPayHistory/?'.http_build_query($data);
            header("Location: ".$url);
            //$this->addPayHistory($openid,$out_trade_no,$total_fee,$transaction_id,1);

            //$sql = "update order set transaction_id = %s where concat('bd_',buyer_id,'_',trip_id) = %s";
            //M()->execute(sprintf($sql,$transaction_id,$out_trade_no));
        } else {
            $result = false;
        }
        // 返回状态给微信服务器
        if ($result) {
            $str = '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        } else {
            $str = '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>';
        }
        echo $str;
        return $str;
    }

    // 添加交易记录信息
    private function addPayHistory($openid,$out_trade_no,$total_fee,$transaction_id,$status) {
        $data = array(
            'openId' => $openid,
            'out_trade_no' => $out_trade_no,
            'total_fee' => $total_fee,
            'transaction_id' => $transaction_id,
            'status' => $status
        );
        $url = 'https://www.saixingchi.com/index.php/Api/Order/addPayHistory?'.http_build_query($data);
        header("Location: ".$url);
    }

    public function FromXml($xml) {
        if(!$xml){
            return "";
        }
        //将XML转为array
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $values;
    }

    public function ToXml($array) {
        if(!is_array($array)|| count($array) <= 0){
            return ;
        }
        $xml = '<xml version="1.0">';
        foreach ($array as $key=>$val){
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
    }

    private function MakeSign($data) {
        //签名步骤一：按字典序排序参数
        ksort($data);
        $string = $this->ToUrlParams($data);
        //签名步骤二：在string后加入KEY
        $string = $string . "&key=43210987659876543210zhangshengli";
        //签名步骤三：MD5加密
        $string = md5($string);
        //签名步骤四：所有字符转为大写
        $result = strtoupper($string);
        return $result;
    }

    private function ToUrlParams($array) {
        $buff = "";
        foreach ($array as $k => $v) {
            if($k != "sign" && $v != "" && !is_array($v)){
                $buff .= $k . "=" . $v . "&";
            }
        }
        $buff = trim($buff, "&");
        return $buff;
    }
}